import React, { Component } from 'react';
import { Button, Form } from 'antd';
import { PageContent } from 'ra-lib';
import config from 'src/commons/config-hoc';

import {
    QueryBar,
    FormRow,
    FormElement,
    Table,
    Operator,
    Pagination,
    batchDeleteConfirm,
} from 'ra-lib';
import EditModal from './EditModal';

@config({
    path: '/kmb-manage',
    ajax: true,
    side: false,

})
export default class Bus extends Component {
    state = {
        loading: false,     // 表格加载数据loading
        dataSource: [],     // 表格数据
        selectedRowKeys: [],// 表格中选中行keys
        total: 0,           // 分页中条数
        pageNum: 1,         // 分页当前页
        pageSize: 20,       // 分页每页显示条数
        deleting: false,    // 批量删除中loading
        visible: false,     // 添加、修改弹框
        id: null,           // 需要修改的数据id
    };

    columns = [
        { title: '巴士路線', dataIndex: 'name',width:50 },
        { title: '車站名稱', dataIndex: 'busstop' ,width:100},
        { title: '坐標', dataIndex: 'location',width:100},
        { title: '距離', dataIndex: 'dist',width:50 },
        {
            title: '操作', dataIndex: 'operator',width:100,
            render: (value, record,index,data) => {
                const { id, name,busstop,children,pid } = record;
                const items = [
                    {
                        label: '編輯',
                        onClick: () => this.setState({ visible: true ,type:!!children?'edit':'editstop', id:!!children?id:pid ,index,children:!children,itemData:record }),
                    },
                    {
                        label: '刪除',
                        color: 'red',
                        confirm: {
                            title: `您確定刪除"${name?name:busstop}"?`,
                            onConfirm: () => this.handleDelete(id,busstop),
                        },
                    },
                ];
                if(children){
                    items.push({
                        label: '線路維護',
                        onClick: () => this.props.history.push({ pathname: "/kmb-map", state: { data:record } }),
                    })
                    items.push({
                        label: '添加站點',
                        onClick: () => this.setState({ visible: true,type:'addstop', id: id ,children:true,itemData:record }),
                    })
                }
                return <Operator items={items}/>;
            },
        },
    ];

    componentDidMount() {
        this.handleSubmit();

    }

    handleSubmit = async () => {
        if (this.state.loading) return;

        const values = await this.form.validateFields();
        //
        // const { pageNum, pageSize } = this.state;
        // const params = {
        //     ...values,
        //     pageNum,
        //     pageSize,
        // };

        this.setState({ loading: true });
        this.props.ajax.get('/api/list')
            .then(res => {
                const dataSource = res?.data || [];
                // const total = res?.total || 0;
                dataSource.forEach(item=>{
                    let id =item.id;
                    item.children.forEach(m=>{
                        m.pid = id;
                    })
                })
                this.setState({ dataSource });
            })
            .finally(() => this.setState({ loading: false }));
    };

    handleDelete = (id,busstop) => {
        if (this.state.deleting) return;

        this.setState({ deleting: true });
        let api =busstop? `/api/delete/busstop/${id}/${busstop}` :`/api/delete/${id}`
        this.props.ajax.del(api, null, { successTip: '删除成功！', errorTip: '删除失败！' })
            .then(() => this.handleSubmit())
            .finally(() => this.setState({ deleting: false }));
    };

    handleBatchDelete = () => {
        if (this.state.deleting) return;

        const { selectedRowKeys } = this.state;
        batchDeleteConfirm(selectedRowKeys.length)
            .then(() => {
                this.setState({ deleting: true });
                this.props.ajax.del('/mock/users', { ids: selectedRowKeys }, { successTip: '删除成功！', errorTip: '删除失败！' })
                    .then(() => {
                        this.setState({ selectedRowKeys: [] });
                        this.handleSubmit();
                    })
                    .finally(() => this.setState({ deleting: false }));
            });
    };

    render() {
        const {
            loading,
            deleting,
            dataSource,
            selectedRowKeys,
            total,
            pageNum,
            pageSize,
            visible,
            id,
            children,
            itemData,
            type,
            index,
            parentData,
            tableChinIndex
        } = this.state;

        const formProps = {
            width: 200,
        };
        const disabledDelete = !selectedRowKeys?.length;
        console.log(dataSource,"dataSourcedataSource");
        return (
            <PageContent>
                <QueryBar>
                    <Form onFinish={() => this.setState({ pageNum: 1 }, () => this.handleSubmit())} ref={form => this.form = form}>
                        <FormRow>
                            <FormElement
                                {...formProps}
                                label="巴士站名稱"
                                name="name"
                            />
                            <FormElement layout>
                                <Button type="primary" htmlType="submit">查詢</Button>
                                <Button onClick={() => this.form.resetFields()}>重置</Button>
                                <Button type="primary" onClick={() => this.setState({ visible: true, id: null,children:false,itemData:null })}>添加</Button>
                                {/*<Button danger loading={deleting} disabled={disabledDelete} onClick={this.handleBatchDelete}>刪除</Button>*/}
                            </FormElement>
                        </FormRow>
                    </Form>
                </QueryBar>

                <Table
                    onRow={(record,index) => {
                        return {
                            onClick: event => {this.setState({tableChinIndex:index})}, // 点击行
                        };
                    }}
                    serialText="序号"
                    loading={loading}
                    columns={this.columns}
                    dataSource={dataSource}
                    rowKey="id"
                    serialNumber
                    // pageNum={pageNum}
                    // pageSize={pageSize}
                />

                {/*<Pagination*/}
                {/*    total={total}*/}
                {/*    pageNum={pageNum}*/}
                {/*    pageSize={pageSize}*/}
                {/*    onPageNumChange={pageNum => this.setState({ pageNum }, () => this.handleSubmit())}*/}
                {/*    onPageSizeChange={pageSize => this.setState({ pageSize, pageNum: 1 }, () => this.handleSubmit())}*/}
                {/*/>*/}

                <EditModal
                    visible={visible}
                    id={id}
                    isEdit={id !== null}
                    children={ children }
                    itemData={ itemData }
                    type={ type }
                    index={ index }
                    tableChinIndex={ tableChinIndex }
                    parentData={ parentData }
                    dataSource={ dataSource }
                    onOk={() => this.setState({ visible: false }, () => this.handleSubmit())}
                    onCancel={() => this.setState({ visible: false })}
                />
            </PageContent>
        );
    }
}
